package lrucache;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Creat with IntelliJ IDEA
 * Description:基于 LinkedHashMap 实现
 * User:WZW
 * Date:2022-10-19
 * Time:23:52
 */
public class LRUCache extends LinkedHashMap<Integer, Integer> {
    public int capacity;
    public LRUCache(int capacity) {
        super(capacity, 0.5f, true);//true表示基于访问顺序
        this.capacity = capacity;
    }

    @Override
    public Integer get(Object key) {
        return super.getOrDefault(key, -1);
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
        return size() > capacity;
    }

    @Override
    public Integer put(Integer key, Integer value) {
        return super.put(key, value);
    }

    public static void main(String[] args) {
        LRUCache lruCache = new LRUCache(3);
        lruCache.put(100,10);
        lruCache.put(110,11);
        lruCache.put(120,12);
        System.out.println(lruCache);
        System.out.println("获取元素");
        System.out.println(lruCache.get(110));
        System.out.println(lruCache);
        System.out.println(lruCache.get(100));
        System.out.println(lruCache);

        System.out.println("存放元素,删除最近最少使用的: ");
        lruCache.put(99,9);

        System.out.println(lruCache);

    }
}
